/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package metier;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import Util.HibernetUtil;

import com.moteur.analysersite.alexa.Alexa;
import com.moteur.analysersite.alexa.AudienceGeographique;
import com.moteur.analysersite.alexa.Keyword;
import com.moteur.analysersite.alexa.UpstreamSites;
import com.moteur.analysersite.builtwith.SiteWebTechnologiesBuiltWith;
import com.moteur.analysersite.builtwith.TechnologieBW;
import com.moteur.analysersite.exceptionPersonnaliser.UrlException;
import com.moteur.analysersite.httpRequestResponse.ResponseHeaderUtil;
import com.moteur.analysersite.performance.TailleSite;
import com.moteur.analysersite.performance.TempsChargement;
import com.moteur.analysersite.seo.Tags_De_La_Page;
import com.moteur.analysersite.util.TimeOut;

import dao.Idao;
import model.Role;
import model.Site;
import model.User;
import model.alexa.Analyse;
import model.alexa.AudienceGeographique_M;
import model.alexa.Keyword_M;
import model.alexa.UpstreamSites_M;
import model.builtwith.AnalyseBuiltwith;
import model.builtwith.Categorie;
import model.builtwith.Thechnologie;
import model.header.AnalyseHeader;
import model.header.Header;
import model.performance.AnalysePerformance;
import model.seo.AnalyseSeo;

/**
 * 
 * @author mehdi
 */
public class MetierImpl implements Imetier {

	private Idao dao;

	public Idao getDao() {
		return dao;
	}

	public MetierImpl() {
		super();
	}

	public void setDao(Idao dao) {
		this.dao = dao;
	}

	public void addUser(User user) {
		dao.addUser(user);
	}

	public List<User> findAllUser() {
		// TODO Auto-generated method stub
		return dao.findAllUser();
	}

	public User findUserByLogin(String login) {
		// TODO Auto-generated method stub
		return dao.findUserByLogin(login);
	}

	public User findUserById(Long id) {
		// TODO Auto-generated
		return dao.findUserById(id);
	}

	public void updateUser(User user) {
		dao.updateUser(user);

	}

	public void deleteUser(Long pk) {
		dao.deleteUser(pk);

	}

	public List<Role> findALLRoll() {

		return dao.findALLRoll();
	}

	public Role findRollbyId(Long pk) {
		// TODO Auto-generated method stub
		return dao.findRollbyId(pk);
	}

	public void addSite(Site site) {
		// TODO Auto-generated method stub
		dao.addSite(site);

	}

	public void updateSite(Site site) {
		// TODO Auto-generated method stub
		dao.updateSite(site);

	}

	public List<Site> findAllSite() {
		// TODO Auto-generated method stub
		return dao.findAllSite();
	}

	public Site findSitebyId(Long pk) {
		// TODO Auto-generated method stub
		return dao.findSitebyId(pk);
	}

	public void deleteSite(Long pk) {
		// TODO Auto-generated method stub
		dao.deleteSite(pk);
	}

	public void ajouterAudiance(Long id) {
		Site s = new Site();
		s = dao.findSitebyId(id);
		System.out.println(s.getUrl_site());
		Analyse anal = new Analyse(s);
	
		
		// d1.ajouterAnalyse(analyse);
		TimeOut timeOutSecond = TimeOut.getInstance();
		
		Document doc;
		List<Keyword_M> ke=new ArrayList<Keyword_M>();
		List<UpstreamSites_M> up1 = new ArrayList<UpstreamSites_M>();
		List<AudienceGeographique_M> aud = new ArrayList<AudienceGeographique_M>();
		try {
			
			doc = Jsoup
					.connect("http://www.alexa.com/siteinfo/"+s.getUrl_site())
					.timeout(timeOutSecond.getTimeout() * 1000).get();
			Alexa alexa = new Alexa(doc);

			List<UpstreamSites> up = new ArrayList<UpstreamSites>();
			List<AudienceGeographique> a = new ArrayList<AudienceGeographique>();
			List<Keyword>keyword=new ArrayList<Keyword>();
			keyword=alexa.keywords();
			a = alexa.audienceGeographique();
			up = alexa.upstreamSites();

			anal.setDate(new Date());
			anal.setClassment(alexa.classementMondial());
			anal.setFidelite(alexa.taux_de_rebond());
			anal.setPagevue(alexa.pageviews_per_visitor());
			anal.setMoyentemps(alexa.time_on_site());

			dao.ajouterAnalyse(anal);
			anal.setPaye(aud);
			anal.setUp(up1);
			anal.setKeyword(ke);
			UpstreamSites_M upstream = new UpstreamSites_M();
			AudienceGeographique_M au = new AudienceGeographique_M();
			
			for (AudienceGeographique aa : a) {
				au.setNom(aa.getPays());
				au.setPourcentage(aa.getPourcentage());
				au.setAnal(anal);

				anal.getPaye().add(au);
				dao.ajouterAudiance(au);
			}

			for (UpstreamSites aa : up) {
				upstream.setSiteUrl(aa.getSiteUrl());
				upstream.setPourcentage(aa.getPourcentage());
				upstream.setAnal(anal);

				anal.getUp().add(upstream);
				dao.ajouterUpstremSite(upstream);
			}
			System.out.println(keyword.size());
			for (Keyword aa : keyword) {
				Keyword_M key=new Keyword_M(aa.getKeyword(), aa.getPourcentage(), anal);
				dao.ajouterKeyword(key);
			}


		} catch (Exception e) {
		}
	}

	public void ajouteranalysebuilth(Long id) {
		Site sit = new Site();
		sit = dao.findSitebyId(id);
		SiteWebTechnologiesBuiltWith site = new SiteWebTechnologiesBuiltWith(
				sit.getUrl_site());

		AnalyseBuiltwith analyse = new AnalyseBuiltwith(new Date(), sit);

		List<String> s = new ArrayList<String>();
		dao.ajouteranalysebuilth(analyse);
		ArrayList<TechnologieBW> technologieSite;
		try {
			technologieSite = site.analyser();
			Session session = HibernetUtil.getSessionFactory().openSession();
			for (TechnologieBW techno : technologieSite) {
				Categorie ca = new Categorie();

				ca.setCategorie(techno.getCategorie());
				ca.setBuilt(analyse);
				analyse.getCat().add(ca);
				dao.ajouterCategorie(ca, session);
				s = techno.getTechnologie();
				for (String s1 : s) {
					Thechnologie tec = new Thechnologie();

					tec.setThechnologie(s1.toString());
					tec.setCat(ca);
					ca.getTech().add(tec);
					dao.ajoutertechnologie(tec, session);
				}
			}
		} catch (UrlException e) {
			e.printStackTrace();
		}
	}

	public void ajouteranalyseheader(Long id) {
		Site site = new Site();
		site = dao.findSitebyId(id);
		AnalyseHeader anal = new AnalyseHeader(new Date(), site);
		dao.ajouteranalyseheader(anal);
		ResponseHeaderUtil siteResponseHeader = new ResponseHeaderUtil(
				"http://" + site.getUrl_site());
		try {
			Session session = HibernetUtil.getSessionFactory().openSession();
			System.out.println("Response Header...\n");
			for (String header : siteResponseHeader.lancer()) {

				System.out.println(header);
				Header head = new Header(header, anal);
				System.out.println(head.getDescription());
				dao.ajouterHeader(head, session);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void ajouteranalysePerformence(Long id) {
		Site site = new Site();
		site = dao.findSitebyId(id);
		AnalysePerformance anal = new AnalysePerformance(new Date(), TempsChargement.
				temps_de_chargement("http://"+site.getUrl_site()), TailleSite
				.getTaille("http://"+site.getUrl_site()) / 1024, site);

//		anal.setTempsReponse(TempsChargement
//				.temps_de_chargement("http://outcomstudio.com/devOs/portfolio/"+site.getUrl_site()));
//		anal.setTaille(TailleSite
//				.getTaille("http://outcomstudio.com/devOs/portfolio/hotel-marrakech") / 1024);
//		anal.setDate(new Date());
//		anal.setSiteP(site);
		dao.ajouteranalysePerformence(anal);

	}

	public void ajouterReferencement(Long id) {
		Site site = new Site();
		site = dao.findSitebyId(id);
		TimeOut timeOutSecond = TimeOut.getInstance();
		Document doc;
		
		
		try{
		doc = Jsoup.connect("http://www.alexa.com/siteinfo/"+site.getUrl_site())
				.timeout(timeOutSecond.getTimeout() * 1000).get();
     Tags_De_La_Page tag=new Tags_De_La_Page(doc);
     
     AnalyseSeo ana=new AnalyseSeo(new Date(),tag.nbr_A_HREF_Externe(),tag.nbr_A_HREF_Interne(),tag.nbrBalise_B_STRONG(),tag.nbrBalise_I_EM(),tag.nbrBaliseH1(),tag.nbrBaliseH2(),tag.nbrBaliseH3(),tag.nbrBaliseTABLE(),tag.nbrBaliseIMG(),tag.nbrBaliseDIV(),site);
    
  dao.ajouterReferencement(ana);
     
		}
		
		catch(Exception e){}
		
	}

	public void deleteUser(String login) {
		dao.deleteUser(login);
		
	}

}
